<?php

namespace App\Services;

use Overtrue\EasySms\EasySms;
use Illuminate\Support\Facades\Cache;

class SmsService 
{
    public function __construct()
    {
        $this->platform = 'aliyun';
        $this->config = $this->getConfig();
    }

    protected function getConfig()
    {
        $config = [
            // HTTP 请求的超时时间（秒）
            'timeout' => 5.0,
            // 默认发送配置
            'default' => [
                // 网关调用策略，默认：顺序调用
                'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,
                // 默认可用的发送网关
                'gateways' => ['aliyun'],
            ],
            // 可用的网关配置
            'gateways' => [
                'errorlog' => [
                    'file' => '/tmp/easy-sms.log',
                ],
                'aliyun' => [
                    'access_key_id' => env('SMS_ACCESS_KEY_ID'),
                    'access_key_secret' => env('SMS_ACCESS_KEY_SECRET'),
                    'sign_name' => '箱宝',
                ],
            ],
        ];
        return $config;
    }

    public function sendVerifyCode($mobile, $len = 4){
        $easySms = new EasySms($this->config);

        $s = pow(10, $len - 1);
        $e = pow(10, $len) -1;
        $randCode = rand($s,$e);
        $res = $easySms->send($mobile, [
            'template' => 'SMS_187590924',
            'data' => [
                'code' => $randCode
            ],
        ]);
        //发送成功
        if ($res[$this->platform]['status'] == 'success' && $res[$this->platform]['result']['Code'] == 'OK') {
            $cacheKey = 'verify_code_'.$mobile;
            Cache::put($cacheKey, $randCode, 5*60);   //有效期5分钟
            return true;
        //发送失败
        } else {
            return false;
        }
    }

    public function checkVerifyCode($mobile, $code){
        $cacheKey = 'verify_code_'.$mobile;
        $cacheCode = Cache::get($cacheKey);
        if ($cacheCode && $cacheCode == $code) {
            return true;
        } else {
            return false;
        }
    }
}